package com.summer.peony.system.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.core.script.DigestUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.summer.peony.common.entity.AjaxResult;
import com.summer.peony.system.mapper.SysUserMapper;
import com.summer.peony.system.mapper.SysUserRoleMapper;
import com.summer.peony.system.pojo.SysUser;
import com.summer.peony.system.pojo.SysUserExample;
import com.summer.peony.system.pojo.SysUserExample.Criteria;
import com.summer.peony.system.pojo.SysUserRoleExample;
import com.summer.peony.system.pojo.SysUserRoleKey;
import com.summer.peony.system.service.SysUserService;

/**
 * @ClassName: SysUserServiceImpl
 * @Description: TODO(用户管理业务逻辑实现层)
 * @author: TaoGe
 * @date: 2020年6月29日 下午2:06:11
 * @version: v0.0.1
 */
@Transactional
@Service
@PropertySource("classpath:application.yml")
public class SysUserServiceImpl implements SysUserService {

	@Autowired
	private SysUserMapper sysUserMapper;

	@Autowired
	private SysUserRoleMapper sysUserRoleMapper;

	@Value("${USER.PASSWORD}")
	private String PASSWORD;

	@Value("${delPath}")
	private String delPath;

	@Override
	public AjaxResult insert(SysUser sysUser) {
		// TODO 新增用户
		Date date = new Date();
		sysUser.setUpdateTime(date);
		sysUser.setCreateTime(date);
		sysUser.setDelFlag("0");
		sysUser.setLockFlag("0");
		sysUser.setPassword(DigestUtils.sha1DigestAsHex(sysUser.getPassword()));
		AjaxResult ajaxResult = new AjaxResult();
		// 判断用户名是否存在
		if (selectUserName(sysUser.getUsername()) > 0) {
			ajaxResult.put("code", 900003);
			ajaxResult.put("msg", "用户名已存在");
			return ajaxResult;
		}
		// 判断手机号是否存在
		if (selectPhone(sysUser.getPhone()) > 0) {
			ajaxResult.put("code", 900004);
			ajaxResult.put("msg", "手机号已存在");
			return ajaxResult;
		}
		// 新增用户
		int insert = sysUserMapper.insert(sysUser);
		int insertUserRole = insertUserRole(sysUser);
		if (insert == 1 && insertUserRole > 0) {
			ajaxResult.put("code", 0);
			ajaxResult.put("msg", "新增成功");
			return ajaxResult;
		}
		ajaxResult.put("code", 999999);
		ajaxResult.put("msg", "新增失败");
		return ajaxResult;
	}

	@Override
	public Integer deleteByPrimaryKey(Integer userId) {
		// TODO 根据id逻辑删除用户
		SysUser sysUser = sysUserMapper.selectByPrimaryKey(userId);
		sysUser.setDelFlag("1");
		return sysUserMapper.updateByPrimaryKey(sysUser);
	}

	@Override
	public AjaxResult updateByPrimaryKey(SysUser sysUser) {
		// TODO 修改用户信息
		SysUser sysUser2 = sysUserMapper.selectByPrimaryKey(sysUser.getUserId());
		Date date = new Date();
		sysUser2.setUpdateTime(date);
		sysUser2.setPassword(DigestUtils.sha1DigestAsHex(sysUser.getPassword()));
		AjaxResult ajaxResult = new AjaxResult();
		// 判断用户名是否存在
		if (selectUserName(sysUser.getUserId(), sysUser.getUsername()) > 0) {
			ajaxResult.put("code", 900003);
			ajaxResult.put("msg", "用户名已存在");
			return ajaxResult;
		}
		// 判断手机号是否存在
		if (selectPhone(sysUser.getUserId(), sysUser.getPhone()) > 0) {
			ajaxResult.put("code", 900004);
			ajaxResult.put("msg", "手机号已存在");
			return ajaxResult;
		}
		sysUser2.setUsername(sysUser.getUsername());
		sysUser2.setPhone(sysUser.getPhone());
		sysUser2.setDeptId(sysUser.getDeptId());
		sysUser2.setSalt(sysUser.getSalt());
		if (sysUser.getAvatar() != sysUser2.getAvatar()) {
			File f1 = new File(delPath + sysUser2.getAvatar());
			boolean delete = f1.delete();
			if (!delete) {
				ajaxResult.put("code", 900013);
				ajaxResult.put("msg", "图片更换失败");
				return ajaxResult;
			}
			sysUser2.setAvatar(sysUser.getAvatar());
		}
		int key = sysUserMapper.updateByPrimaryKey(sysUser2);
		sysUserRoleMapper.deleteUserRoleByUserId(sysUser2.getUserId());
		int insertUserRole = insertUserRole(sysUser);
		if (key == 1 && insertUserRole > 0) {
			ajaxResult.put("code", 0);
			ajaxResult.put("msg", "修改成功");
			return ajaxResult;
		}
		ajaxResult.put("code", 999999);
		ajaxResult.put("msg", "修改失败");
		return ajaxResult;
	}

	@Override
	public PageInfo<SysUser> selectAllUsers(String username, String phone, Integer pageNum, Integer pageSize) {
		// TODO 分页查询用户
		SysUserExample example = new SysUserExample();
		Criteria criteria = example.createCriteria();
		criteria.andDelFlagEqualTo("0").andUsernameLike("%" + username + "%").andPhoneLike("%" + phone + "%");
		PageHelper.startPage(pageNum, pageSize);
		List<SysUser> list = sysUserMapper.selectByExample(example);
		for (SysUser sysUser : list) {
			SysUserRoleExample example2 = new SysUserRoleExample();
			com.summer.peony.system.pojo.SysUserRoleExample.Criteria criteria2 = example2.createCriteria();
			criteria2.andUserIdEqualTo(sysUser.getUserId());
			List<SysUserRoleKey> list2 = sysUserRoleMapper.selectByExample(example2);
			sysUser.setPassword("");
			if (!list2.isEmpty()) {
				sysUser.setRoleIds(sysUserRoleMapper.getAllRoleIds(sysUser.getUserId()));
			}
		}
		PageInfo<SysUser> pageInfo = new PageInfo<SysUser>(list);
		return pageInfo;
	}

	@Override
	public SysUser selectByPrimaryKey(Integer userId) {
		// TODO 根据id查询用户
		return sysUserMapper.selectByPrimaryKey(userId);
	}

	// 查询是有有相同用户名
	private int selectUserName(String sysUserName) {
		SysUserExample example = new SysUserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUsernameEqualTo(sysUserName);
		List<SysUser> selectByExample = sysUserMapper.selectByExample(example);
		return selectByExample.size();
	}

	// 查询是有有相同手机号
	private int selectPhone(String phone) {
		SysUserExample example = new SysUserExample();
		Criteria criteria = example.createCriteria();
		criteria.andPhoneEqualTo(phone);
		List<SysUser> selectByExample = sysUserMapper.selectByExample(example);
		return selectByExample.size();
	}

	// 查询是有有相同用户名
	private int selectUserName(int userId, String sysUserName) {
		SysUserExample example = new SysUserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUserIdNotEqualTo(userId).andUsernameEqualTo(sysUserName);
		List<SysUser> selectByExample = sysUserMapper.selectByExample(example);
		return selectByExample.size();
	}

	// 查询是有有相同手机号
	private int selectPhone(int userId, String phone) {
		SysUserExample example = new SysUserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUserIdNotEqualTo(userId).andPhoneEqualTo(phone);
		List<SysUser> selectByExample = sysUserMapper.selectByExample(example);
		return selectByExample.size();
	}

	@Override
	public Integer userPwd(Integer userId) {
		// 重置密码
		SysUser sysUser = sysUserMapper.selectByPrimaryKey(userId);
		sysUser.setPassword(DigestUtils.sha1DigestAsHex(PASSWORD));
		return sysUserMapper.updateByPrimaryKey(sysUser);
	}

	/**
	 * @Description: TODO(新增用户角色)
	 * @param sysUser
	 * @return int
	 * @author: TaoGe
	 * @date: 2021年1月28日 下午2:33:59
	 * @throws:
	 */
	public int insertUserRole(SysUser sysUser) {
		int rows = 1;
		SysUserExample example = new SysUserExample();
		Criteria criteria = example.createCriteria();
		criteria.andPhoneEqualTo(sysUser.getPhone());
		List<SysUser> list2 = sysUserMapper.selectByExample(example);
		if (list2.isEmpty()) {
			return 2;
		}
		Integer userId = list2.get(0).getUserId();
		// 新增用户与角色管理
		List<SysUserRoleKey> list = new ArrayList<SysUserRoleKey>();
		for (Integer roleId : sysUser.getRoleIds()) {
			SysUserRoleKey rm = new SysUserRoleKey();
			rm.setUserId(userId);
			rm.setRoleId(roleId);
			list.add(rm);
		}
		if (list.size() > 0) {
			rows = sysUserRoleMapper.batchUserRole(list);
		}
		return rows;
	}
}
